//
//  WPhotosBrowserView.m
//  PhotosBrowser
//
//  Created by winter on 2016/10/24.
//  Copyright © 2016年 JHJR. All rights reserved.
//

#import "WPhotosBrowserView.h"
#import "WPhotoBrowserConst.h"
#import "WPhotoShowView.h"
#import "WPhotoShowCell.h"
#import "WPhotoModel.h"

@interface WPhotosBrowserView ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;

/** 缩略图 数组 */
@property (nonatomic, copy) NSArray *thumbnailUrls;

/** 图片地址数组*/
@property (nonatomic, copy) NSArray *imageUrls;

/** 用来记录当前下标 */
@property (nonatomic, assign) NSInteger currentIndex;

@property (nonatomic, strong) NSArray<WPhotoModel *> *cellDatas;
@end

@implementation WPhotosBrowserView

+ (instancetype)photosBrowserView
{
    WPhotosBrowserView *view = [WPhotosBrowserView photosBrowserViewWithDelegate:nil dataSource:nil];
    return view;
}

+ (instancetype)photosBrowserViewWithDelegate:(id<WPhotosBrowserViewDelegate>)delegate
{
    WPhotosBrowserView *view = [WPhotosBrowserView photosBrowserViewWithDelegate:delegate
                                                                      dataSource:nil];
    return view;
}

+ (instancetype)photosBrowserViewWithDataSource:(id<WPhotosBrowserViewDataSource>)dataSource
{
    WPhotosBrowserView *view = [WPhotosBrowserView photosBrowserViewWithDelegate:nil
                                                                      dataSource:dataSource];
    return view;
}

+ (instancetype)photosBrowserViewWithDelegate:(id<WPhotosBrowserViewDelegate>)delegate dataSource:(id<WPhotosBrowserViewDataSource>)dataSource
{
    WPhotosBrowserView *view = [[WPhotosBrowserView alloc] init];
    if (dataSource) {
        view.dataSource = dataSource;
    }
    if (delegate) {
        view.delegate = delegate;
    }
    return view;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    frame = CGRectMake(0, 0, WRealyScreenW, WRealyScreenH);
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubViews];
    }
    return self;
}

- (void)setupSubViews
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = WScreenSize;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    [self addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass:[WPhotoShowCell class] forCellWithReuseIdentifier:@"cell"];
}

- (void)showWithIndex:(NSInteger)index
{
    if ([self.dataSource respondsToSelector:@selector(imageUrlsForBrowserWithView:)]) {
        self.imageUrls = [self.dataSource imageUrlsForBrowserWithView:self];
    }
    
    self.currentIndex = index;
    if (self.currentIndex+1 > self.imageUrls.count) {
        NSLog(@"【WPhotoShowView】-currentIndexWithView: 返回的index超出范围");
        return;
    }
    
    // 数据
    if ([self.dataSource respondsToSelector:@selector(thumbnailUrlsForBrowserWithView:)]) {
        self.thumbnailUrls = [self.dataSource thumbnailUrlsForBrowserWithView:self];
    }
    
    BOOL yesOrNo = YES;
    if (self.thumbnailUrls.count != self.imageUrls.count) {
        NSLog(@"【WPhotoShowView】-thumbnailUrlForBrowserWithView: 返回的地址数组数目与 -imagesUrlForBrowserWithView: 返回的不相符");
        yesOrNo = NO;
    }
    [self convertDataWithThumbnailUrls:yesOrNo];
    
    [self.collectionView reloadData];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    
    [self show];
}

- (void)show
{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview:self];
    
    if (![self.dataSource respondsToSelector:@selector(photosBrowserViewWillShowAtLocationViewWithIndex:)]) {
        return;
    }
    UIView *fromView = [self.dataSource photosBrowserViewWillShowAtLocationViewWithIndex:self.currentIndex];
    
    CGRect fromFrame = [fromView convertRect:fromView.frame toView:window];
    
    WPhotoShowCell *cell = (WPhotoShowCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentIndex inSection:0]];
    
//    self.collectionView.alpha = 0;
//    [cell.photoShowView animateWithFromFrame:fromFrame animations:^{
//        self.collectionView.alpha = 1;
//    }];
}

- (void)hideWithIndex:(NSInteger)index
{
    [self removeFromSuperview];
}

- (void)convertDataWithThumbnailUrls:(BOOL)yesOrNo
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.imageUrls.count];
    int index = 0;
    for (id obj in self.imageUrls) {
        
        WPhotoModel *model = [WPhotoModel photoWithOriginalUrl:obj];
        if (yesOrNo) {
            model.thumbnailImageUrl = self.thumbnailUrls[index];
        }
        [array addObject:model];
        index++;
    }
    
    self.cellDatas = [array copy];
}

#pragma mark - collectionView delegate & datasource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.cellDatas.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WPhotoShowCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.photoModel = self.cellDatas[indexPath.item];
    __weak typeof(self) weakSelf = self;
    cell.actionBlock = ^(PhotoViewActionType action){
        if (PhotoViewActionType_singleTap == action) {
            NSLog(@"imageTapAction");
            [weakSelf hideWithIndex:indexPath.item];
        }
        else {
            NSLog(@"imageDidLongPress");
        }
    };
    return cell;
}

#pragma mark - scrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.imageUrls.count == 0) {
        return;
    }
    int index = (scrollView.contentOffset.x + self.collectionView.bounds.size.width * 0.5) / self.collectionView.bounds.size.width;
    int pageControlIndex = index % self.imageUrls.count;
    
    if (self.currentIndex == pageControlIndex) {
        return;
    }
    self.currentIndex = pageControlIndex;
    
    NSLog(@"show index = %ld", self.currentIndex);
}

#pragma mark - lazy

@end

